package org.lc.stk.service.bank.impl;

import org.lc.stk.model.banks.Bank;

import java.util.List;
import java.util.stream.Collectors;

import org.lc.stk.dao.bank.MultiCourseBankRepository;
import org.lc.stk.model.banks.MultiCourseBank;
import org.lc.stk.model.course.Course;
import org.lc.stk.model.question.attrs.DifficultySchema;
import org.lc.stk.model.question.attrs.QuestionType;
import org.lc.stk.service.bank.MultiCourseBankService;
import org.lc.stk.service.course.CourseService;
import org.lc.stk.service.exception.BusinessException;
import org.lc.stk.web.dto.bank.MultiCourseBankDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MultiCourseBankServiceImpl implements MultiCourseBankService {

    @Autowired
    private MultiCourseBankRepository bankRepository;

    @Autowired
    private CourseService courseService;

    @Override
    @Transactional
    public MultiCourseBank create(MultiCourseBankDTO dto) {
        // 验证名称是否重复
        if (bankRepository.existsByNameAndIdNot(dto.getName(), null)) {
            throw new BusinessException("已存在同名题库");
        }

        MultiCourseBank bank = new MultiCourseBank();
        bank.setName(dto.getName());
        bank.setState(dto.getState() == 1 ? Bank.BankState.ACTIVE : Bank.BankState.INACTIVE);

        // 设置关联课程
        if (dto.getCourseIds() != null && !dto.getCourseIds().isEmpty()) {
            List<Course> courses = dto.getCourseIds().stream()
                .map(id -> {
                    Course course = courseService.findById(id);
                    if (course == null) {
                        throw new BusinessException("课程不存在: " + id);
                    }
                    return course;
                })
                .collect(Collectors.toList());
            bank.setCourses(courses);
        }

        if (dto.getQuestionTypeIds() != null) {
            List<QuestionType> questionTypes = dto.getQuestionTypeIds().stream()
                .map(this::getQuestionType)
                .collect(Collectors.toList());
            bank.setQuestionTypes(questionTypes);
        }

        if (dto.getDifficultySchemaId() != null) {
            DifficultySchema schema = getDifficultySchema(dto.getDifficultySchemaId());
            bank.setDifficultySchema(schema);
        }

        return bankRepository.save(bank);
    }

    @Override
    @Transactional
    public MultiCourseBank update(Integer id, MultiCourseBankDTO dto) {
        MultiCourseBank bank = getById(id);
        if (bank == null) {
            throw new BusinessException("题库不存在");
        }

        // 验证名称是否重复
        if (bankRepository.existsByNameAndIdNot(dto.getName(), id)) {
            throw new BusinessException("已存在同名题库");
        }

        bank.setName(dto.getName());
        bank.setState(dto.getState() == 1 ? Bank.BankState.ACTIVE : Bank.BankState.INACTIVE);

        // 更新关联课程
        if (dto.getCourseIds() != null) {
            List<Course> courses = dto.getCourseIds().stream()
                .map(courseId -> {
                    Course course = courseService.findById(courseId);
                    if (course == null) {
                        throw new BusinessException("课程不存在: " + courseId);
                    }
                    return course;
                })
                .collect(Collectors.toList());
            bank.setCourses(courses);
        }

        if (dto.getQuestionTypeIds() != null) {
            List<QuestionType> questionTypes = dto.getQuestionTypeIds().stream()
                .map(this::getQuestionType)
                .collect(Collectors.toList());
            bank.setQuestionTypes(questionTypes);
        }

        if (dto.getDifficultySchemaId() != null) {
            DifficultySchema schema = getDifficultySchema(dto.getDifficultySchemaId());
            bank.setDifficultySchema(schema);
        }

        return bankRepository.save(bank);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        MultiCourseBank bank = getById(id);
        if (bank == null) {
            throw new BusinessException("题库不存在");
        }
        
        // TODO: 检查题库是否被使用
        bank.setState(Bank.BankState.INACTIVE); // 逻辑删除

        bankRepository.save(bank);
    }

    @Override
    public MultiCourseBank getById(Integer id) {
        return bankRepository.findById(id)
            .orElseThrow(() -> new BusinessException("题库不存在"));
    }

    @Override
    public Page<MultiCourseBank> query(
        String name, 
        Integer state, 
        Pageable pageable
    ) {
        return bankRepository.findByConditions(name, state, pageable);
    }

    @Override
    public boolean isNameExists(String name, Integer excludeId) {
        return bankRepository.existsByNameAndIdNot(name, excludeId);
    }

    private QuestionType getQuestionType(Integer id) {
        // TODO: 从QuestionTypeService获取题型
        throw new UnsupportedOperationException("Not implemented");
    }

    private DifficultySchema getDifficultySchema(Integer id) {
        // TODO: 从DifficultySchemaService获取难度方案
        throw new UnsupportedOperationException("Not implemented");
    }
}
